import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:get/get.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/view/pick/secret/secret_item.dart';
import 'package:sports_new/widgets/card.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/score_prediction_widget.dart';
import '../../../controller/match/detail/match_intelligence_logic.dart';
import '../../../widgets/base/qkd_text.dart';
import '../../../widgets/ads_label.dart';

class ZqMatchInfoView extends StatefulWidget {
  const ZqMatchInfoView({super.key});

  @override
  State<ZqMatchInfoView> createState() => _ZqMatchInfoViewState();
}

class _ZqMatchInfoViewState extends State<ZqMatchInfoView>
    with AutomaticKeepAliveClientMixin, TickerProviderStateMixin {
  late ZqMatchInfoLogic logic;

  @override
  void initState() {
    super.initState();
    logic = Get.put(ZqMatchInfoLogic(), tag: '${Get.arguments}');
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return GetBuilder<ZqMatchInfoLogic>(
        tag: '${Get.arguments}',
        builder: (logic) => LoadingWidget<int>(
              isLoading: false,
              data: logic.data?.toJson().values.map((e) => e).toList().join(),
              child: () => SingleChildScrollView(
                physics: const ClampingScrollPhysics(),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const AdsLabel(
                      adsTag: "match_zq_爆料",
                      tapType: 'ggw_bsxq_bl',
                      margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
                    ),
                    block<bool>(
                      data: logic.secret.noValue,
                      child: secret()
                    ).paddingOnly(top: 8),
                    block<String>(
                      data: (logic.data?.homeNews ?? "") +
                        (logic.data?.guestNews ?? ""),
                      child: gen()
                    ),
                    block<String>(
                        data: (logic.data?.matchData ?? "") +
                            (logic.data?.matchForecast ?? ""),
                        child: analysis()),
                    LoadingWidget<String>(
                      isLoading: false,
                      data: (logic.data?.homeScore ?? "") +
                          (logic.data?.guestScore ?? ""),
                      noData: Container(),
                      child: () => ScorePredictionWidget(
                              homeLogo: logic.detail?.homeLogo ?? "",
                              homeName: logic.detail?.homeName ?? "",
                              guestLogo: logic.detail?.guestLogo ?? "",
                              guestName: logic.detail?.guestName ?? "",
                              homeScore: logic.data?.homeScore ?? "",
                              guestScore: logic.data?.guestScore ?? "")
                          .paddingOnly(left: 16, right: 16, bottom: 10),
                    ),
                    block<String>(
                        data: (logic.data?.homeAnalysis ?? "") +
                            (logic.data?.guestAnalysis ?? ""),
                        child: strength()),
                    block<String>(
                        data: (logic.data?.homeInjury ?? "") +
                            (logic.data?.guestInjury ?? ""),
                        child: suspend()),
                    block<int>(data: logic.totalLength, child: _intelligence()),
                    block<String>(
                        data: (logic.data?.confident ?? "") +
                            (logic.data?.vsInfo ?? ""),
                        child: _favorSuggest()),
                    Container(height: 60)
                  ],
                ),
              ),
            ));
  }

  Widget block<T>({required T data, required Widget child}) {
    return LoadingWidget<T>(
      isLoading: false,
      data: data,
      noData: Container(),
      child: () => Container(
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(8)),
        margin: const EdgeInsets.only(bottom: 10, left: 8, right: 8),
        child: child,
      ),
    );
  }

  Widget _favorSuggest() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Container(width: 4),
            Image.asset(width: 24, Utils.getImgPath("match_info_favor.png")),
            Container(width: 2),
            QkdText("心水建议", fontSize: 16,fontWeight: FontWeight.w500),
          ],
        ),
        Container(height: 12),
        Block(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 16),
            child: Column(
              children: [
                if (logic.data?.confident != "")
                Padding(
                  padding: const EdgeInsets.only(bottom: 10),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      _dot(),
                      Container(width: 3),
                      QkdText(logic.data?.confident ?? "",
                        fontSize: 15,
                        height: 1.4,
                        color: const Color(0xFF444444)
                      ),
                      RatingBar(
                        initialRating: logic.data?.stars?.toDouble() ?? 0,
                        allowHalfRating: true,
                        itemCount: 5,
                        itemSize: 16,
                        ignoreGestures: true,
                        unratedColor: Colours.grey99,
                        ratingWidget: RatingWidget(
                          full: Image.asset(
                            width: 16,
                            color: Colours.main,
                            Utils.getImgPath("match_info_star_on.png")
                          ),
                          half: Image.asset(
                              width: 16,
                              Utils.getImgPath("match_info_star_half.png")
                          ),
                          empty: Image.asset(
                            width: 16,
                            Utils.getImgPath("match_info_star_off.png")
                          )
                        ),
                        onRatingUpdate: (rating) => 0
                      )
                    ]
                  ),
                ),
                if (logic.data?.vsInfo != "") _paragraph(logic.data?.vsInfo ?? "")
              ],
            ),
          )
        )
      ],
    );
  }

  Widget _intelligence() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Container(width: 4),
            Image.asset(
                width: 24, Utils.getImgPath("match_info_important.png")),
            Container(width: 2),
            QkdText("重要情报", fontSize: 16,fontWeight: FontWeight.w500),
          ],
        ),
        Container(height: 12),
        TabBlock(
          tabs: List.generate(2, (index) => tabHead(index == 0 ? true : false)),
          pages: List.generate(2, (index) => Padding(
            padding: const EdgeInsets.symmetric(
              horizontal: 12, vertical: 16),
            child: Column(
              children: [
                _intelligenceContent(
                    logic.intelligence?[index == 0?0:1],
                    name: "有利情报"),
                Container(height: 8),
                _intelligenceContent(logic.intelligence?[4],
                    name: "中立情报"),
                Container(height: 8),
                _intelligenceContent(
                    logic.intelligence?[index == 0?2:3],
                    name: "不利情报")
              ],
            ),
          ))
        )
      ],
    );
  }

  Widget gen() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Container(width: 4),
            Image.asset(
                width: 24, Utils.getImgPath("match_info_worldwide.png")),
            Container(width: 2),
            QkdText("精选情报", fontSize: 16,fontWeight: FontWeight.w500),
          ],
        ),
        Container(height: 12),
        TabBlock(
            tabs:
                List.generate(2, (index) => tabHead(index == 0 ? true : false)),
            pages: List.generate(2, (index) {
              var data = index == 0
                  ? logic.data?.homeNews?.split(RegExp(r"[\f\r\n\t\v]+"))
                  : logic.data?.guestNews?.split(RegExp(r"[\f\r\n\t\v]+"));
              return Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: List.generate(
                          data?.length ?? 0,
                          (index) => data![index] != ""
                              ? _paragraph(data[index])
                              : Container()))
                  .paddingSymmetric(vertical: 16, horizontal: 12);
            }))
      ],
    );
  }

  Widget analysis() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Container(width: 4),
            Image.asset(width: 24, Utils.getImgPath("match_info_analysis.png")),
            Container(width: 2),
            QkdText("赛事解析", fontSize: 16,fontWeight: FontWeight.w500),
          ],
        ),
        Container(height: 12),
        Block(
            child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 16),
          child: Column(
            children: [
              _intelligenceContent(
                  logic.data?.matchData?.split(RegExp(r"[\f\r\n\t\v]+")),
                  name: "赛事数据"),
              Container(height: 10),
              _intelligenceContent(
                  logic.data?.matchForecast?.split(RegExp(r"[\f\r\n\t\v]+")),
                  name: "赛事预测")
            ],
          ),
        ))
      ],
    );
  }

  Widget strength() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Container(width: 4),
            Image.asset(width: 24, Utils.getImgPath("match_info_strength.png")),
            Container(width: 2),
            QkdText("实力定位", fontSize: 16,fontWeight: FontWeight.w500),
          ],
        ),
        Container(height: 12),
        TabBlock(
            tabs:
                List.generate(2, (index) => tabHead(index == 0 ? true : false)),
            pages: [
              _intelligenceContent(
                logic.data?.homeAnalysis?.split(RegExp(r"[\f\r\n\t\v]+")),
              ).paddingSymmetric(vertical: 16, horizontal: 12),
              _intelligenceContent(
                logic.data?.guestAnalysis?.split(RegExp(r"[\f\r\n\t\v]+")),
              ).paddingSymmetric(vertical: 16, horizontal: 12)
            ])
      ],
    );
  }

  Widget _intelligenceContent(List? data, {String? name, Widget? asset}) {
    return data == null || data.isEmpty ? Container()
    : Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(children: [
          if (asset != null)
            Container(
                width: 20,
                height: 20,
                margin: const EdgeInsets.only(right: 5),
                child: asset),
          if (name != null)
            Padding(
              padding: const EdgeInsets.only(bottom: 10),
              child: QkdText(name,
                fontWeight: FontWeight.w500,
                needCenter: true
              ),
            ),
        ]),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: List.generate(
              data.length,
              (index) => data[index] != ""
                ? _paragraph(data[index])
                : Container()
          )
        )
      ],
    );
  }

  Widget suspend() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Container(width: 4),
            Image.asset(width: 24, Utils.getImgPath("match_info_suspend.png")),
            Container(width: 2),
            QkdText("球员伤停", fontSize: 16,fontWeight: FontWeight.w500),
          ],
        ),
        Container(height: 12),
        Block(
            child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 16),
          child: Column(children: [
            Row(children: [
              Expanded(child: suspendHead(true)),
              Expanded(child: suspendHead(false))
            ]),
            Container(height: 10),
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  child: suspendList(logic.homeSuspend, true),
                ),
                Container(width: 10),
                Expanded(child: suspendList(logic.guestSuspend, false))
              ],
            ),
            Container(height: 10),
            _intelligenceContent(
                logic.data?.injuryAnalysis?.split(RegExp(r"[\f\r\n\t\v]+")),
                name: "伤停解读"),
          ]),
        ))
      ],
    );
  }

  Widget secret(){
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Container(width: 4),
            Image.asset(
                width: 24, Utils.getImgPath("match_info_secret.png")),
            Container(width: 2),
            const QkdText("海外情报", fontSize: 16,fontWeight: FontWeight.w500),
          ],
        ),
        Container(height: 12),
        if(logic.secret?.where((e) => e.canRead != true).toList().length.hasValue == true)
          SecretItem.detail(
            count: logic.secret?.where((e) => e.canRead != true).toList().length,
            onChange: (change) {
              if(change == true) logic.getData();
            }
          ).paddingOnly(bottom: 8),
        ...logic.secret?.where(
          (element) => element.canRead == true
        ).map<Widget>(
          (e) => SecretItem.detail(
            secret: e,
            onChange: (change) {
              if(change == true) logic.getData();
            }
          )
        ).toList().insertEvery(Container(height: 8)) ?? []
      ],
    );
  }

  Widget tabHead(bool isHome) {
    return Row(mainAxisSize: MainAxisSize.min, children: [
      CachedNetworkImage(
          width: 20,
          height: 20,
          fit: BoxFit.fitWidth,
          errorWidget: (
            context,
            url,
            error,
          ) =>
              Image.asset(Utils.getImgPath("zq_placeholder.png")),
          placeholder: (context, url) => Styles.placeholderIcon(),
          imageUrl: isHome
              ? logic.detail?.homeLogo ?? ""
              : logic.detail?.guestLogo ?? ""),
      Container(width: 4),
      QkdText(isHome
          ? logic.detail?.homeName ?? ""
          : logic.detail?.guestName ?? ""),
    ]);
  }

  Widget _dot() {
    return Container(
        width: 10,
        height: 4,
        alignment: Alignment.centerLeft,
        decoration:
            const BoxDecoration(shape: BoxShape.circle, color: Colours.main)
    );
  }

  Widget _paragraph(String text,{bool needDot = true}) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 4),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          if(needDot)
          Padding(
            padding: const EdgeInsets.only(top: 10, right: 3),
            child: _dot(),
          ),
          Flexible(
            child: QkdText(
              text.split(" ").join().split("").join("\u200A").trim(),
              fontSize: 14,
              height: 1.6,
              color: const Color(0xFF444444),
              letterSpacing: -0.3,
              textAlign: TextAlign.justify,
            )
          ),
        ],
      ),
    );
  }

  Widget suspendHead(bool isHome) {
    var list = [
      CachedNetworkImage(
          width: 32,
          height: 32,
          errorWidget: (
            context,
            url,
            error,
          ) =>
              Image.asset(Utils.getImgPath("zq_placeholder.png")),
          placeholder: (context, url) => Styles.placeholderIcon(),
          imageUrl: isHome
              ? logic.detail?.homeLogo ?? ""
              : logic.detail?.guestLogo ?? ""),
      Container(width: 4),
      QkdText(
        isHome ? logic.detail?.homeName ?? "" : logic.detail?.guestName ?? ""
      )
    ];
    return Row(
      mainAxisAlignment:
          isHome ? MainAxisAlignment.start : MainAxisAlignment.end,
      children: isHome ? list : list.reversed.toList(),
    );
  }

  Widget suspendList(List<List<String>> data, bool isHome) {
    return LoadingWidget<bool>(
      isLoading: false,
      data: data.any((element) => !element.hasValue),
      noData: Container(
        alignment: Alignment.topCenter,
        padding: const EdgeInsets.symmetric(vertical: 18),
        child: QkdText('暂无数据', fontSize: 11, color: Colours.grey99),
      ),
      child: () => Column(
        children: List.generate(
            data.length,
            (index) => Padding(
                  padding:
                      EdgeInsets.only(bottom: index < data.length - 1 ? 4 : 0),
                  child: suspendPlayer(data[index], isHome),
                )),
      ),
    );
  }

  Widget suspendPlayer(List<String>? list, bool isHome) {
    return !(list?.length ?? 0).hasValue
        ? Container()
        : SizedBox(
            height: 60,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Container(height: 4),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(child: QkdText(list?[0] ?? "")),
                    if((list?.length??0) > 4)
                    Container(
                      height: 14,
                      padding: const EdgeInsets.symmetric(horizontal: 2),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          color:
                              isHome ? Colours.main : Colours.blue2766D6,
                          borderRadius:
                              const BorderRadius.all(Radius.circular(2))),
                      child: QkdText(
                        list?[4] ?? "",
                        needCenter: true,
                        fontSize: 10, color: Colours.white, height: 1
                      ),
                    )
                  ],
                ),
                Container(height: 8),
                Row(
                  children: [
                    if((list?.length??0) > 1)
                    Container(
                        height: 14,
                        padding: const EdgeInsets.symmetric(horizontal: 2),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            border: Border.all(
                                width: 0.5,
                                color: isHome
                                    ? Colours.main
                                    : Colours.blue2766D6),
                            borderRadius:
                                const BorderRadius.all(Radius.circular(2))),
                        child: QkdText(
                          list?[1] ?? "",
                          needCenter: true,
                          fontSize: 10,
                          color: isHome ? Colours.main : Colours.blue2766D6,
                          height: 1
                        )),
                    if((list?.length??0) > 3)
                    Container(
                      height: 14,
                      margin: const EdgeInsets.only(left: 4),
                      padding: const EdgeInsets.symmetric(horizontal: 2),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          border: Border.all(
                              width: 0.5,
                              color: isHome
                                  ? Colours.main
                                  : Colours.blue2766D6),
                          borderRadius:
                              const BorderRadius.all(Radius.circular(2))),
                      child: QkdText(
                        list?[3] ?? "",
                        needCenter: true,
                        fontSize: 10,
                        color:
                        isHome ? Colours.main : Colours.blue2766D6,
                        height: 1
                      ),
                    ),
                    if((list?.length??0) > 2)
                    QkdText(list?[2] ?? "",
                      fontSize: 11, color: Colours.grey99
                    ).paddingOnly(left: 4)
                  ],
                )
              ],
            ),
          );
  }

  @override
  bool get wantKeepAlive => true;
}
